package com.example.configDataSource;

import com.example.constant.DataSourceConst;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Step3:将所有的数据源存放至AbstractRoutingDataSource
 * nextStep:{@link DynamicDataSource}
 */
@Configuration
public class DataSourceConfig {

  /**
   * 注入AbstractRoutingDataSource
   * @param readDruidDataSource
   * @param writeDruidDataSource
   * @return
   * @throws Exception
   */
  @Bean
  public AbstractRoutingDataSource routingDataSource(
      @Qualifier(DataSourceConst.READ_DATASOURCE_KEY) DataSource readDruidDataSource,
      @Qualifier(DataSourceConst.WRITE_DATASOURCE_KEY) DataSource writeDruidDataSource
  ) throws Exception {
    DynamicDataSource dataSource = new DynamicDataSource();
    Map<Object, Object> targetDataSources = new HashMap();
    targetDataSources.put(DataSourceConst.WRITE_DATASOURCE_KEY, writeDruidDataSource);
    targetDataSources.put(DataSourceConst.READ_DATASOURCE_KEY, readDruidDataSource);
    /*设置所有的数据源*/
    dataSource.setTargetDataSources(targetDataSources);
    /*指定默认的数据源*/
    dataSource.setDefaultTargetDataSource(writeDruidDataSource);
    return dataSource;
  }
}